package org.idea.qiyu.framework.datasource.aop;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.idea.qiyu.framework.datasource.annotation.Datasource;
import org.idea.qiyu.framework.datasource.config.DataSourceContextHolder;
import org.idea.qiyu.framework.datasource.properties.MultiDataSourceProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 动态数据源前面
 *
 * @Author linhao
 * @Date created in 11:28 上午 2021/5/25
 */
@Aspect
@Component
@Order(2)
public class DynamicDatasourceAspect {

    @Autowired
    private MultiDataSourceProperties multiDataSourceProperties;

    @Pointcut("@within(org.idea.qiyu.framework.datasource.annotation.Datasource) || " +
            "@annotation(org.idea.qiyu.framework.datasource.annotation.Datasource)")
    public void pointCut(){

    }

    @Before("pointCut()  && @annotation(datasource)")
    public void doBefore(Datasource datasource){
        System.out.println("---- select datasource ---- " + datasource.value());
        DataSourceContextHolder.setDatasource(datasource.value());
    }

    @After("pointCut()")
    public void doAfter(){
        DataSourceContextHolder.clearDatasource();
    }
}
